<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- element-ui中传默认参数：$event -->
      <el-card shadow="never">
        学科名称
        <div style="display: inline-block;width:200px;margin:0 20px">
          <el-input v-model="input"></el-input>
        </div>
        <el-button @click="moveSearch">清除</el-button>
        <el-button type="primary" @click="searchSubject">搜索</el-button>
        <el-button
          type="success"
          icon="el-icon-edit"
          style="float:right"
          @click="addSubjectsFn">新增学科</el-button>
        <div style="padding: 10px 15px;margin: 15px 0;color: #6e6e6e;background-color: #ddd;font-size:14px">
          <i class="el-icon-info"></i>
          数据一共 {{ counts }} 条
        </div>
        <el-form style="margin-top: 25px">
          <el-card style="margin-top: 10px">
            <el-table border :data="list">
              <el-table-column
                label="序号"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="学科名称" prop="subjectName" />
              <el-table-column label="创建者" prop="username" />
              <el-table-column label="创建日期" prop="addDate" width="200">
                <template #default="{ row }">
                  {{ formateData(row.timeOfEntry) }}
                </template>
              </el-table-column>
              <el-table-column label="前台是否显示" prop="isFrontDisplay" :formatter="formatterDisplay"/>
              <el-table-column
                label="二级目录"
                prop="twoLevelDirectory"
              />
              <el-table-column label="标签" prop="tags" />
              <el-table-column label="题目数量" prop="totals" />
              <el-table-column label="操作" fixed="right" width="280">
                <template #default="{row}">
                  <!-- v-if="checkPermission('EMP_CHANGE')" -->
                  <el-button
                    type="text"
                    size="small"
                    @click="$router.push(`/subjects/directorys?id=${row.id}&name=${row.subjectName}`)"
                  >学科分类</el-button>
                  <!-- v-if="checkPermission('EMP_ASSIGNROLE')" -->
                  <el-button
                    type="text"
                    size="small"
                    @click="$router.push(`/subjects/tags?id=${row.id}&name=${row.subjectName}`)"
                  >学科标签</el-button>
                  <!-- v-if="checkPermission('EMP_DELEMPLOYEES')" -->
                  <el-button
                    type="text"
                    size="small"
                    @click="editSubjectsFn(row)"
                  >修改</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="delsubject(row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div style="height: 60px; margin-top: 25px;float:right">
              <el-pagination
                background
                :current-page="page"
                :page-size="pagesize"
                layout="prev, pager, next,sizes,jumper"
                :total="counts"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[10, 8, 5]"
              />
            </div>
          </el-card>
          <el-form-item>

          </el-form-item>
        </el-form>
      </el-card>
      <addsubjects :showDialog.sync="showDialog"/>
      <el-dialog
        title="修改学科"
        :visible="showDialogEdit"
        @close="closeDialogFn"
        top="20vh"
        width="30%">
        <!-- 表单 -->
        <el-form label-width="100px" :model="formData" :rules="rules" ref="editSubject">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input
              v-model="formData.subjectName"
              style="width: 85%"
              placeholder="请输入学科名称"></el-input>
          </el-form-item>
          <el-form-item label="是否显示" prop="isFrontDisplay" required>
            <el-switch
              style="width: 85%"
              v-model="display"
              active-color="#13ce66">
            </el-switch>
          </el-form-item>
        </el-form>
        <!-- footer插槽 -->
        <template v-slot:footer>
          <el-button @click="closeDialogFn">取消</el-button>
          <el-button type="primary" @click="formEdit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list, update, remove, simple, detail } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'
import addsubjects from '@/module-hmmm/components/subjects-add.vue'
export default {
  props: {
    showDialog2: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      input: '',
      page: 1,
      pagesize: 10,
      list: [], // 从接口处取回
      counts: 0,
      showDialog: false,
      showDialogEdit: this.showDialog2,
      editRow: {},
      formData: {
        subjectName: '',
        isFrontDisplay: 1
      },
      display: true,
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    addsubjects
  },
  methods: {
    // 点击搜索按钮，查询并更新列表
    async searchSubject () {
      const { data: data1 } = await simple(this.input)
      const arr1 = []
      const arr2 = []
      data1.forEach(item1 => {
        if (item1.label.includes(this.input)) {
          // 提取出符合搜索要求的数据的id值
          arr1.push(item1.value)
        }
      })
      // 对比所有数据的id值，筛选出符合条件的数据
      const { data: data2 } = await list()
      data2.items.forEach(item2 => {
        arr1.forEach(item3 => {
          if (item2.id === item3) {
            arr2.push(item2)
          }
        })
      })
      console.log(arr2)
      this.list = arr2
      this.counts = arr2.length
    },
    // 点击清除，清空输入框
    moveSearch () {
      this.input = ''
      this.subjectsList()
    },
    // 点击确定按钮
    formEdit () {
      this.$refs.editSubject.validate(async flag => {
        if (!flag) return
        // 当flag不等于false时，将数据传入需要调用的接口
        this.formData.isFrontDisplay = this.display ? 1 : 0
        await update(this.formData)
        this.$message.success('修改学科成功')
        this.closeDialogFn()
        // 重置数据
        this.subjectsList()
      })
    },
    // 关闭弹窗
    closeDialogFn () {
      this.showDialogEdit = false
      // 重置(绑定了校验的)数据
      this.$refs.editSubject.resetFields()
    },
    // 新增学科弹窗
    addSubjectsFn () {
      this.showDialog = true
    },
    // 修改学科弹窗
    async editSubjectsFn (row) {
      this.showDialogEdit = true
      const { data } = await detail(row)
      this.formData = data
      this.display = this.formData.isFrontDisplay === 1 ? !false : false
      console.log(data)
      console.log(this.formData.subjectName, this.formData.isFrontDisplay)
    },
    // 删除操作
    delsubject (row) {
      this.$confirm('此操作将永久删除该学科，是否继续？', '提示')
        .then(async () => {
          // 表示用户点击了确定按钮
          await remove(row)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.subjectsList()
        })
        .catch(() => {})
    },
    // 格式化内容，将1和0渲染为是和否
    formatterDisplay (row, column, cellValue, index) {
      if (cellValue === 1) {
        return '是'
      } else if (cellValue === 0) {
        return '否'
      }
    },
    // 通过dayjs组件实现时间格式化
    formateData (time) {
      return dayjs(time).format('YYYY-MM-DD hh:mm:ss')
    },
    // 通过序号来实现，删除当前页的最后一条数据时，自动跳转到前一页
    indexMethod (index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 每页条数改变时触发函数
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      this.subjectsList()
    },
    // 分页当前页
    handleCurrentChange (val) {
      this.page = val
      this.subjectsList()
      console.log(this.page)
    },
    // 数据渲染
    async subjectsList () {
      const { data } = await list({ page: this.page, pagesize: this.pagesize })
      console.log(data)
      this.list = data.items
      this.counts = data.counts
    }
  },
  created () {
    this.subjectsList()
  }
}
</script>

<style scoped>
</style>
